package com.qyhl.webtv.module_microvideo.shortvideo.classic.news;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ClassicHomeNewsFragment extends BaseFragment implements ClassicHomeNewsContract.ClassicHomeNewsView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refreshLayout;

    private String sectionId;

    private CommonAdapter<NewsBean> commonAdapter;

    private List<NewsBean> mDataList = new ArrayList<>();

    private ClassicHomeNewsPresenter mPresenter;

    private boolean hasMore;

    private String newsId = "0";

    private int page = 1;

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }

    public void setSectionId(String sectionId) {
        if (StringUtils.isEmpty(sectionId)) {
            this.sectionId = "0";
        } else {
            this.sectionId = sectionId;
        }

    }

    public static ClassicHomeNewsFragment newInstance(String sectionId) {
        ClassicHomeNewsFragment fragment = new ClassicHomeNewsFragment();
        fragment.setSectionId(sectionId);
        fragment.setHasMore(false);
        return fragment;
    }

    public static ClassicHomeNewsFragment newInstance(String sectionId, boolean hasMore) {
        ClassicHomeNewsFragment fragment = new ClassicHomeNewsFragment();
        fragment.setSectionId(sectionId);
        fragment.setHasMore(hasMore);
        return fragment;
    }

    @Override
    public void initImmersionBar() {

    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.micro_fragment_classic_home_news, null);
    }

    @Override
    protected void create() {
        mPresenter = new ClassicHomeNewsPresenter(this);
        loadMask.setStatus(LoadingLayout.Loading);

        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        if (hasMore) {
            refreshLayout.setEnableLoadMore(true);
            refreshLayout.setEnableRefresh(true);
        } else {
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.setEnableRefresh(false);
        }

        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        recycleView.setAdapter(commonAdapter = new CommonAdapter<NewsBean>(getContext(), R.layout.micro_item_classic_home_news, mDataList) {
            @Override
            protected void convert(ViewHolder holder, NewsBean bean, int position) {
                holder.setText(R.id.title, bean.getTitle());
                if (StringUtils.isNotEmpty(bean.getCatalogName())) {
                    holder.setVisible(R.id.source, true);
                    holder.setText(R.id.source, bean.getCatalogName());
                } else {
                    holder.setVisible(R.id.source, false);
                }

                holder.setText(R.id.summary, bean.getSummary());

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ClassicHomeNewsFragment.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);
            }
        });


        if (StringUtils.isNotEmpty(sectionId)) {
            if (Integer.parseInt(sectionId) >= 1000000) {
                mPresenter.getData(sectionId, page + "");
            } else {
                mPresenter.getData(sectionId, newsId);
            }
        }
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                newsId = "0";
                if (Integer.parseInt(sectionId) >= 1000000) {
                    mPresenter.getData(sectionId, page + "");
                } else {
                    mPresenter.getData(sectionId, newsId);
                }
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                newsId = "0";
                if (Integer.parseInt(sectionId) >= 1000000) {
                    mPresenter.getData(sectionId, page + "");
                } else {
                    mPresenter.getData(sectionId, newsId);
                }
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (Integer.parseInt(sectionId) >= 1000000) {
                    mPresenter.getData(sectionId, page + "");
                } else {
                    mPresenter.getData(sectionId, newsId);
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                NewsBean bean = mDataList.get(position);
                switch (mDataList.get(position).getType()) {
                    case "1"://普通新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                    }
                    break;
                    case "2"://图片新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        bundle.putString("section", bean.getCatalogID());
                        RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                    }

                    break;
                    case "3"://直播
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("newsId", bean.getID());
                        bundle.putString("liveType", bean.getLivetype());
                        RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
                    }
                    break;
                    case "4"://标题新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        bundle.putString("title", bean.getTitle());
                        bundle.putString("url", bean.getRedirectURL());
                        RouterManager.router(ARouterPathConstant.ADV, bundle);
                    }
                    break;
                    case "5"://视频新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                    }
                    break;
                    case "8"://互动直播
                        break;
                    case "101"://抓取新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                    }
                    break;
                    default:
                        break;

                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @Override
    public void setData(List<NewsBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            mDataList.clear();
        }

        if (StringUtils.isNotEmpty(sectionId)) {
            if (Integer.parseInt(sectionId) >= 1000000) {
                page++;
            } else {
                try {
                    newsId = beanList.get(beanList.size() - 1).getID();
                } catch (Exception e) {
                    newsId = "-1";
                }
            }
        } else {
            newsId = "-1";
        }

        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！");
            }
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }


}
